package hikari.preferences.device_parameters;

import hikari.persistence.propertieseditor.editors.HelpProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * @author sad
 */
public class XMLHelpManager extends HelpProvider {

    private Map<String, String> map = new HashMap<>();

    public XMLHelpManager(File file) throws Exception {
        InputStream stream = new FileInputStream(file);
        read(stream);
    }

    public XMLHelpManager(InputStream stream) throws Exception {
        read(stream);
    }

    private void read(InputStream stream) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setCoalescing(true);
        Document document = factory.newDocumentBuilder().parse(stream);

        NodeList topics = document.getElementsByTagName("topic");
        for (int i = 0; i < topics.getLength(); i++) {
            Element topic = (Element) topics.item(i);
            processTopic(topic);
        }
    }

    private void processTopic(Element topic) {
        String id = topic.getAttribute("id");
        if (id == null || id.isEmpty()) {
            throw new RuntimeException("Help file cannot contain topic without id attribute");
        }

        NodeList values = topic.getElementsByTagName("value");
        if (values.getLength() == 0) {
            String helpText = topic.getTextContent();
            addToMap("&" + id, helpText);
        } else {
            for (int i = 0; i < values.getLength(); i++) {
                Element value = (Element) values.item(i);
                String valueId = value.getAttribute("id");
                String helpText = value.getTextContent();
                addToMap("&" + id + valueId, helpText);
            }
        }
    }

    private void addToMap(String key, String text) {
        text = text.replaceAll("^[\\s]*", "").replaceAll("[\\s]*$", "");
        map.put(key, text);
    }

    @Override
    public String getHelp(String topic, Object value) {
        String key = "&" + topic + value.toString();
        if (map.containsKey(key)) {
            return map.get(key);
        } else {
            key = "&" + topic;
            if (map.containsKey(key)) {
                return map.get(key);
            } else {
                return topic;
            }
        }
    }
}